#include "MemmoryHandler.h"
#include <iostream>

using namespace std;

MemmoryHandler* MemmoryHandler::g_pkInstance = NULL;

MemmoryHandler *MemmoryHandler::GetInstance()
{
	if (g_pkInstance == NULL)
	{
		g_pkInstance = new MemmoryHandler();
	}

	return g_pkInstance;
}

MemmoryHandler::MemmoryHandler(void)
{
}

MemmoryHandler::~MemmoryHandler(void)
{
}


void MemmoryHandler::registerIntoMemMap(void *pointer, size_t size, bool isArray, int line, char *file)
{
	MEM_INFO info;
	info.memSize = size;
	info.fileName = file;
	info.line = line;
	info.isArray = isArray;
	
	std::pair<void*, MEM_INFO> pair(pointer, info);

	m_pkMemMap.insert(pair);
}

void MemmoryHandler::unregisterOfMemMap(void *p)
{
	std::map<void*, MEM_INFO>::iterator it = m_pkMemMap.begin();

	while(it != m_pkMemMap.end())
	{
		if ((*it).first == p)
		{
			m_pkMemMap.erase(it);
		}

		it++;
	}
}

void MemmoryHandler::printMemMap()
{
	std::map<void*, MEM_INFO>::iterator it = m_pkMemMap.begin();

	while(it != m_pkMemMap.end())
	{
		MEM_INFO memData = (*it).second;


	    cout<<"Pointer "<<(*it).first<<endl;

		string fName(memData.fileName);

		size_t lastBarIdx = fName.find_last_of("/\\");
		string fileName = fName.substr(lastBarIdx+1, std::string.npos);

		cout<<"Declared in "<<fileName.c_str()<<endl;
		cout<<"In line " <<memData.line<<endl;
		cout<<"Is leaking memmory "<<memData.memSize<<endl;
		cout<<"Note: Is Array - "<<memData.isArray<<std::endl;

		it++;
	}
}